<template>
  <div>
    <a-card>
      <a-row :gutter="20">
        <a-col :span="6">
          <a-input-search
            v-model="queryParams.username"
            placeholder="输入用户名查找"
            enter-button
            allowClear
            @search="getCateList"
          />
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="addCate">新增</a-button>
        </a-col>
      </a-row>

      <a-table
        rowKey="username"
        :columns="columns"
        :pagination="pagination"
        :dataSource="userList"
        bordered
        @change="handleTableChange"
      >
        <span slot="role" slot-scope="role">{{
          role === 1 ? '管理员' : '订阅者'
        }}</span>

        <template slot="action" slot-scope="data">
          <div class="actionSlot">
            <a-button
              icon="edit"
              type="primary"
              style="margin-right:15px"
              @click="editCate(data.ID)"
              >编辑</a-button
            >
            <a-button
              icon="delete"
              type="danger"
              style="margin-right:15px"
              @click="deleteCate(data.ID)"
              >删除</a-button
            >
            <a-button icon="info" type="info" @click="deleteCate(data.ID)"
              >重置</a-button
            >
          </div>
        </template>
      </a-table>
    </a-card>

    <!-- 新增用户区域 -->
    <a-modal
      closable
      title="新增用户"
      :visible="addCateVisible"
      width="30%"
      @ok="addCateOK"
      @cancel="addCateCancel"
      :destroyOnClose="true"
    >
      <a-form-model :model="newCate" :rules="addCateRules" ref="addCateRef">
        <a-form-model-item has-feedback label="用户名" prop="username">
          <a-input v-model="newCate.username"></a-input>
        </a-form-model-item>

        <a-form-model-item has-feedback label="密码" prop="password">
          <a-input-password v-model="newCate.password"></a-input-password>
        </a-form-model-item>

        <a-form-model-item has-feedback label="确认密码" prop="checkpass">
          <a-input-password v-model="newCate.checkpass"></a-input-password>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 编辑用户区域 -->
    <a-modal
      closable
      title="编辑用户"
      :visible="editCateVisible"
      width="30%"
      @ok="editCateOK"
      @cancel="editCateCancel"
      :destroyOnClose="true"
    >
      <a-form-model :model="userInfo" :rules="userRules" ref="editCateRef">
        <a-form-model-item has-feedback label="用户名" prop="username">
          <a-input v-model="userInfo.username"></a-input>
        </a-form-model-item>

        <a-form-model-item label="是否为管理员" prop="role">
          <a-switch
            checkedChildren="是"
            unCheckedChildren="否"
            v-model="isAdministrator"
            @change="adminChange"
          ></a-switch>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    title: 'ID',
    dataIndex: 'ID',
    width: '10%',
    key: 'id',
    scopedSlots: { customRender: 'name' },
    align: 'center',
  },
  {
    title: '用户名',
    dataIndex: 'username',
    width: '20%',
    key: 'username',
    align: 'center',
  },
  {
    title: '角色',
    dataIndex: 'role',
    width: '20%',
    key: 'role',
    scopedSlots: { customRender: 'role' },
    align: 'center',
  },
  {
    title: '操作',
    width: '30%',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
  },
]

export default {
  data () {
    return {
      pagination: {
        pageSizeOptions: ['5', '10', '20'],
        pageSize: 5,
        total: 0,
        showSizeChanger: true,
        showTotal: total => `共${total}条`,
      },
      userList: [],
      columns,
      isAdministrator: false,
      queryParams: {
        username: '',
        pagesize: 5,
        pagenum: 1,
      },
      userInfo: {
        id: 0,
        username: '',
        password: '',
        checkpass: '',
        role: 2,
      },
      newCate: {
        id: 0,
        username: '',
        password: '',
        checkpass: '',
        role: 2,
      },
      addCateRules: {
        username: [
          { required: true, message: '请输入用户名！', trigger: 'blur' },
          {
            min: 4,
            max: 12,
            message: '用户名必须在4~12个之间！',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码！', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '密码必须在6~20个之间！',
            trigger: 'blur',
          },
        ],
        checkpass: [
          {
            validator: (rule, value, callback) => {
              if (this.newCate.checkpass === '') {
                callback(new Error('请再次输入密码！'))
              }
              if (this.newCate.checkpass !== this.newCate.password) {
                callback(new Error('密码不一致，请确认输入密码！'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
      },
      userRules: {
        username: [
          { required: true, message: '请输入用户名！', trigger: 'blur' },
          {
            min: 4,
            max: 12,
            message: '用户名必须在4~12个之间！',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码！', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '密码必须在6~20个之间！',
            trigger: 'blur',
          },
        ],
        checkpass: [
          {
            validator: (rule, value, callback) => {
              if (this.userInfo.checkpass === '') {
                callback(new Error('请再次输入密码！'))
              }
              if (this.userInfo.checkpass !== this.userInfo.password) {
                callback(new Error('密码不一致，请确认输入密码！'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
      },
      visible: false,
      addCateVisible: false,
      editCateVisible: false,
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('users', {
        params: {
          username: this.queryParams.username,
          pagesize: this.queryParams.pagesize,
          pagenum: this.queryParams.pagenum,
        },
      })
      if (res.status !== 200) return this.$message.error(res.message)
      this.userList = res.data
      this.pagination.total = res.total
    },
    // 更改分页
    handleTableChange (pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.queryParams.pagesize = pagination.pageSize
      this.queryParams.pagenum = pagination.current

      if (pagination.pageSize !== this.pagination.pageSize) {
        this.queryParams.pagenum = 1
        pager.current = 1
      }
      this.pagination = pager
      this.getCateList()
    },
    // 删除用户
    deleteCate (id) {
      this.$confirm({
        title: '提示：请再次确认！',
        content: '确定要删除该用户吗？一旦删除无法取消！',
        onOk: async () => {
          const { data: res } = await this.$http.delete(`user/${id}`)
          if (res.status !== 200) return this.$message.error(res.message)
          this.$message.success('删除成功！')
          this.getCateList()
        },
        onCancel: () => {
          this.$message.info('已取消删除！')
        },
      })
    },
    // 新增用户按钮
    addCate () {
      this.addCateVisible = true
    },
    // 新增用户
    addCateOK () {
      this.$refs.addCateRef.validate(async valid => {
        if (!valid) return this.$message.error('参数不符合要求，请重新输入！')
        const { data: res } = await this.$http.post('user/add', {
          username: this.newCate.username,
          password: this.newCate.password,
          role: this.newCate.role,
        })
        if (res.status !== 200) return this.$message.error(res.message)
        this.addCateVisible = false
        this.$message.success('用户添加成功！')
        this.getCateList()
      })
    },
    addCateCancel () {
      this.$refs.addCateRef.resetFields()
      this.addCateVisible = false
      this.$message.info('添加用户已取消！')
    },
    adminChange (checked) {
      if (checked) {
        this.userInfo.role = 1
      } else {
        this.userInfo.role = 2
      }
    },
    // 编辑用户
    async editCate (id) {
      this.editCateVisible = true
      const { data: res } = await this.$http.get(`user/${id}`)
      this.userInfo = res.data
      this.isAdministrator = res.data.role === 1
      this.userInfo.id = id
    },
    editCateOK () {
      this.$refs.editCateRef.validate(async valid => {
        if (!valid) return this.$message.error('参数不符合要求，请重新输入！')
        const { data: res } = await this.$http.put(`user/${this.userInfo.id}`, {
          username: this.userInfo.username,
          role: this.userInfo.role,
        })
        if (res.status !== 200) return this.$message.error(res.message)
        this.editCateVisible = false
        this.$message.success('更新用户信息成功！')
        this.getCateList()
      })
    },
    editCateCancel () {
      this.$refs.editCateRef.resetFields()
      this.editCateVisible = false
      this.$message.info('编辑已取消！')
    },
  },
}
</script>

<style scoped>
.actionSlot {
  display: flex;
  justify-content: center;
}
.ant-table {
  margin-top: 15px;
}
</style>
